﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using SimulationCore.Net.DTO;
using SimulationPresenter.Presentation.Helpers;
using SimulationPresenter.Presentation.Primitives;
using SimulationPresenter.Simulation.Helpers;
using SimulationPresenter.Simulation.Primitive;
using SimulationPresenter.Theater.Enums;
using VertexShape = SimulationPresenter.Presentation.Primitives.ColoredVertexShape;

namespace SimulationPresenter.Theater.Actors
{
    internal class MetalClothActor : Actor, ISimulatable, ITypeDiscoverableActor, IActorPropertiesProvider, IDrawable
    {
        private IPresentationPrimitive shape;
        private MetalCloth state;

        internal MetalClothActor(MetalCloth state)
        {
            this.state = state;
        }

        public void UpdateState(IList<ActorState> actorsState)
        {
            try
            {
                var actorState = state.FindOwnState(actorsState) as ClothState;
                var previousColor = null == shape ? Color.DarkSlateGray : shape.Color;

                shape = new VertexShape(actorState.Vertices,
                                    actorState.Normals,
                                    actorState.indices,
                                    previousColor) as IPresentationPrimitive;

                //Todo: remove the HACK!
                shape.Color = previousColor;
            }
            catch (DataException)
            {
                //Todo: Log error
                return;
            }
        }

        public ActorType ActorType
        {
            get { return ActorType.Cloth; }
        }

        public bool Visible
        {
            get { return null == shape ? false : shape.Visible; }
            set
            {
                if (null != shape)
                {
                    shape.Visible = value;
                }
            }
        }

        public Vector3 Position
        {
            get
            {
                //Todo: Return real postion
                return new Vector3(-1, -1, -1);
            }
        }

        public string Name
        {
            get { return null == state ? "Unknown" : state.Name;}
        }

        public void DrawActor(Device device)
        {
            if (null != shape)
            {
                IndexedVerticesDrawer.Draw(shape, Matrix.Identity, device); 
            }
        }

        public void Highlight(Color color)
        {
            if (null != shape)
            {
                shape.Color = color;
            }
        }
        
        override public string ToString()
        {
            return null == state ? "Undefined" : state.Name;
        }
    }
}
